package com.dlc.shop.user.common.service.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dlc.shop.user.common.dao.PopupUserLogMapper;
import com.dlc.shop.user.common.model.PopupUserLog;
import com.dlc.shop.user.common.service.PopupUserLogService;
import com.dlc.shop.user.common.vo.CostPerPopupVO;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 弹窗广告用户日志
 * @author TRACK
 */
@Service
@AllArgsConstructor
public class PopupUserLogServiceImpl extends ServiceImpl<PopupUserLogMapper, PopupUserLog> implements PopupUserLogService {

    private final PopupUserLogMapper popupUserLogMapper;
    private static final String TIME_FORMAT = "yyMMdd";

    @Override
    public void insert(PopupUserLog log) {
        log.setCreateTime(Integer.valueOf(DateUtil.format(new Date(), TIME_FORMAT)));
        popupUserLogMapper.insert(log);
    }

    @Override
    public void removeByPopupId(Long popupId) {
        popupUserLogMapper.deleteById(popupId);
    }

    @Override
    public List<PopupUserLog> getByCondition(String userId, String uuid, CostPerPopupVO costPerPopup) {
        PopupUserLog popupUserLog = new PopupUserLog();
        popupUserLog.setPopupId(costPerPopup.getPopupId());
        if (Objects.nonNull(userId)) {
            popupUserLog.setUserId(userId);
        } else {
            popupUserLog.setUuid(uuid);
        }
        if (Objects.nonNull(costPerPopup.getWeekFrequency())) {
            // 按周推送校验今天有没有推送过
            Integer maxTime = Integer.valueOf(DateUtil.format(new Date(), TIME_FORMAT));
            Integer minTime = Integer.valueOf(DateUtil.format(DateUtil.beginOfDay(new Date()), TIME_FORMAT));
            popupUserLog.setMaxTime(maxTime);
            popupUserLog.setMinTime(minTime);
        }
        if (Objects.nonNull(costPerPopup.getDayFrequency())) {
            // 按天推送校验x天前到今天有没有推送过
            Integer maxTime = Integer.valueOf(DateUtil.format(new Date(), TIME_FORMAT));
            Integer minTime = Integer.valueOf(DateUtil.format(DateUtil.beginOfDay(DateUtil.offsetDay(new Date(), -costPerPopup.getDayFrequency())), TIME_FORMAT));
            popupUserLog.setMaxTime(maxTime);
            popupUserLog.setMinTime(minTime);
        }
        return popupUserLogMapper.getByCondition(popupUserLog);
    }
}
